#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TVBox站点完整功能测试器
模拟APP中的真实使用场景，预测站点在APP中的表现
"""

import json
import os
import re
import time
import glob
import requests
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin, quote
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning

disable_warnings(InsecureRequestWarning)


class CompleteSiteTester:
    """完整站点功能测试器"""

    def __init__(
        self, config_path="config.json", pre_check_path="scripts/config_pre_check.json"
    ):
        self.session = requests.Session()
        self.session.headers.update(
            {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                "Accept": "application/json, text/plain, */*",
                "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            }
        )
        self.session.verify = False
        self.config_path = config_path
        self.pre_check_path = pre_check_path

    def load_sites(self, config_path=None):
        """加载站点配置"""
        if config_path is None:
            config_path = self.pre_check_path
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)["sites"]

    def load_full_config(self, config_path=None):
        """加载完整配置"""
        if config_path is None:
            config_path = self.pre_check_path
        with open(config_path, "r", encoding="utf-8") as f:
            return json.load(f)

    def extract_rule_details(self, ext_path):
        """深度解析规则文件"""
        if not os.path.exists(ext_path):
            return None

        try:
            with open(ext_path, "r", encoding="utf-8") as f:
                content = f.read()

            # 检查是否有var rule定义
            if "var rule" not in content:
                return {"error": "缺少rule定义", "content_preview": content[:200]}

            # 提取关键字段
            rule_info = {}
            patterns = {
                "title": r'title\s*:\s*[\'"]([^\'"]*)[\'"]',
                "host": r'host\s*:\s*[\'"]([^\'"]*)[\'"]',
                "homeUrl": r'homeUrl\s*:\s*[\'"]([^\'"]*)[\'"]',
                "searchUrl": r'searchUrl\s*:\s*[\'"]([^\'"]*)[\'"]',
                "detailUrl": r'detailUrl\s*:\s*[\'"]([^\'"]*)[\'"]',
                "url": r'url\s*:\s*[\'"]([^\'"]*)[\'"]',
                "class_name": r'class_name\s*:\s*[\'"]([^\'"]*)[\'"]',
                "class_url": r'class_url\s*:\s*[\'"]([^\'"]*)[\'"]',
            }

            for key, pattern in patterns.items():
                match = re.search(pattern, content)
                if match:
                    rule_info[key] = match.group(1)

            # 检查功能实现
            rule_info.update(
                {
                    "has_search": bool(re.search(r"(搜索|searchUrl)", content)),
                    "has_detail": bool(re.search(r"(二级|detailUrl)", content)),
                    "has_category": bool(re.search(r"(一级|class_name)", content)),
                    "has_filter": "filter" in content and "filterable" in content,
                    "has_lazy": "lazy" in content,
                    "has_推荐": "推荐" in content,
                    "content_size": len(content),
                    "syntax_complete": all(
                        x in content for x in ["var rule", "{", "}"]
                    ),
                }
            )

            # 检查可能的语法错误
            issues = []
            if not rule_info.get("host"):
                issues.append("缺少host定义")
            if not rule_info.get("title"):
                issues.append("缺少title定义")
            if not rule_info.get("searchUrl") and rule_info.get("has_search"):
                issues.append("声明有搜索功能但缺少searchUrl")
            if not rule_info.get("detailUrl") and rule_info.get("has_detail"):
                issues.append("声明有详情功能但缺少detailUrl")

            rule_info["potential_issues"] = issues
            return rule_info

        except Exception as e:
            return {"error": f"文件解析错误: {str(e)}"}

    def test_basic_connectivity(self, host, timeout=10):
        """基础连通性测试"""
        if not host:
            return {"status": "error", "message": "Host为空"}

        if not host.startswith(("http://", "https://")):
            host = "http://" + host

        try:
            start_time = time.time()
            response = self.session.get(host, timeout=timeout)
            response_time = round((time.time() - start_time) * 1000, 1)

            result = {
                "status": "success" if 200 <= response.status_code < 400 else "warning",
                "status_code": response.status_code,
                "response_time": response_time,
                "content_type": response.headers.get("content-type", ""),
                "server": response.headers.get("server", ""),
                "ssl": host.startswith("https://"),
                "redirected": len(response.history) > 0,
                "final_url": response.url,
                "content_length": len(response.content),
                "encoding": response.encoding,
            }

            # 检查响应内容
            if response.status_code == 200:
                content = response.text[:1000]  # 只检查前1000字符
                content_lower = content.lower()

                # 检查各种错误指示
                error_indicators = [
                    "error",
                    "错误",
                    "failed",
                    "失败",
                    "stopped",
                    "停止",
                    "suspended",
                    "暂停",
                    "not found",
                    "未找到",
                    "access denied",
                    "拒绝访问",
                    "sorry",
                    "抱歉",
                    "website has been stopped",
                    "站点已停止",
                    "网站已关闭",
                ]

                for indicator in error_indicators:
                    if indicator in content_lower:
                        result["content_warning"] = (
                            f"页面显示错误信息: 包含'{indicator}'"
                        )
                        result["status"] = "error"  # 修改状态为错误
                        break

                if len(content) < 100:
                    result["content_warning"] = "页面内容过少，可能异常"

            return result

        except requests.exceptions.RequestException as e:
            # 统一处理所有requests库的异常
            if isinstance(e, requests.exceptions.Timeout):
                message = "连接超时"
            elif isinstance(e, requests.exceptions.SSLError):
                message = "SSL证书错误"
            elif isinstance(e, requests.exceptions.ConnectionError):
                message = "连接失败"
            else:
                message = f"请求异常: {str(e)}"
            return {"status": "error", "message": message}
        except Exception as e:
            return {"status": "error", "message": f"未知错误: {str(e)}"}

    def test_search_functionality(self, host, search_url_template):
        """测试搜索功能"""
        if not search_url_template or not host:
            return {"status": "skip", "message": "缺少搜索URL配置"}

        try:
            # 构建测试搜索URL
            test_keyword = "电影"
            search_url = search_url_template.replace("**", quote(test_keyword))
            search_url = search_url.replace("fypage", "1")
            full_url = urljoin(host, search_url)

            response = self.session.get(full_url, timeout=8)

            result = {
                "status": "success" if response.status_code == 200 else "error",
                "test_url": full_url,
                "status_code": response.status_code,
                "response_size": len(response.content),
                "content_type": response.headers.get("content-type", ""),
            }

            if response.status_code == 200:
                content = response.text
                # 检查返回内容类型
                if "application/json" in response.headers.get("content-type", ""):
                    try:
                        data = response.json()
                        if isinstance(data, dict):
                            result["json_valid"] = True
                            result["has_data"] = bool(
                                data.get("data")
                                or data.get("list")
                                or data.get("results")
                            )
                        else:
                            result["json_valid"] = False
                    except:
                        result["json_valid"] = False
                else:
                    # HTML内容检查
                    result["has_content"] = len(content) > 500
                    result["has_video_refs"] = any(
                        x in content.lower() for x in ["video", "mp4", "m3u8", "movie"]
                    )

            return result

        except Exception as e:
            return {"status": "error", "message": f"搜索测试失败: {str(e)}"}

    def test_category_functionality(self, host, home_url, url_template):
        """测试分类功能"""
        if not url_template or not host:
            return {"status": "skip", "message": "缺少分类URL配置"}

        try:
            # 构建测试分类URL
            test_url = url_template.replace("fyclass", "1").replace("fypage", "1")
            if "fyfilter" in test_url:
                test_url = test_url.replace("fyfilter", "")

            full_url = urljoin(host, test_url)

            response = self.session.get(full_url, timeout=8)

            result = {
                "status": "success" if response.status_code == 200 else "error",
                "test_url": full_url,
                "status_code": response.status_code,
                "response_size": len(response.content),
            }

            if response.status_code == 200:
                content = response.text
                # 检查内容有效性
                if "application/json" in response.headers.get("content-type", ""):
                    try:
                        data = response.json()
                        result["json_valid"] = True
                        result["has_list"] = bool(data.get("data") or data.get("list"))
                    except:
                        result["json_valid"] = False
                else:
                    result["has_content"] = len(content) > 200

            return result

        except Exception as e:
            return {"status": "error", "message": f"分类测试失败: {str(e)}"}

    def test_detail_functionality(self, host, detail_url_template):
        """测试详情功能"""
        if not detail_url_template or not host:
            return {"status": "skip", "message": "缺少详情URL配置"}

        try:
            # 构建测试详情URL
            test_id = "123"  # 使用通用测试ID
            detail_url = detail_url_template.replace("fyid", test_id)
            full_url = urljoin(host, detail_url)

            response = self.session.get(full_url, timeout=8)

            result = {
                "status": "success" if response.status_code in [200, 404] else "error",
                "test_url": full_url,
                "status_code": response.status_code,
                "response_size": len(response.content),
            }

            # 404是正常的，因为测试ID可能不存在
            if response.status_code in [200, 404]:
                result["endpoint_valid"] = True
                if response.status_code == 200:
                    content = response.text
                    if "application/json" in response.headers.get("content-type", ""):
                        try:
                            data = response.json()
                            result["json_valid"] = True
                        except:
                            result["json_valid"] = False

            return result

        except Exception as e:
            return {"status": "error", "message": f"详情测试失败: {str(e)}"}

    def comprehensive_site_test(self, site):
        """对单个站点进行全面测试"""
        site_name = site.get("name", "Unknown")
        site_key = site.get("key", "unknown")
        ext_path = site.get("ext", "").replace("./", "")

        print(f"🔍 深度测试站点: {site_name}")

        result = {
            "name": site_name,
            "key": site_key,
            "ext_file": ext_path,
            "test_time": datetime.now().isoformat(),
            "overall_status": "unknown",
            "app_usability": "unknown",
            "rule_analysis": {},
            "connectivity_test": {},
            "functionality_tests": {},
            "app_predictions": {},
            "critical_issues": [],
            "warnings": [],
            "recommendations": [],
        }

        # 1. 规则文件深度分析
        rule_info = self.extract_rule_details(ext_path)
        result["rule_analysis"] = rule_info

        if not rule_info or rule_info.get("error"):
            result["overall_status"] = "error"
            result["app_usability"] = "unusable"
            result["critical_issues"].append("规则文件无法解析，APP中会崩溃或无法加载")
            return result

        host = rule_info.get("host")
        if not host:
            result["overall_status"] = "error"
            result["app_usability"] = "unusable"
            result["critical_issues"].append("缺少host配置，APP无法连接到站点")
            return result

        # 2. 基础连通性测试
        connectivity = self.test_basic_connectivity(host)
        result["connectivity_test"] = connectivity

        if connectivity["status"] == "error":
            result["overall_status"] = "error"
            result["app_usability"] = "unusable"
            result["critical_issues"].append(
                f"站点无法访问，APP中会显示连接错误: {connectivity.get('message', '')}"
            )
            return result

        # 3. 功能性测试
        tests = {}

        # 搜索功能测试
        if rule_info.get("searchUrl"):
            search_test = self.test_search_functionality(host, rule_info["searchUrl"])
            tests["search"] = search_test
            if search_test["status"] == "error":
                result["critical_issues"].append("搜索功能异常，APP中搜索会失败")

        # 分类功能测试
        if rule_info.get("url"):
            category_test = self.test_category_functionality(
                host, rule_info.get("homeUrl"), rule_info["url"]
            )
            tests["category"] = category_test
            if category_test["status"] == "error":
                result["critical_issues"].append("分类列表异常，APP中无法显示内容列表")

        # 详情功能测试
        if rule_info.get("detailUrl"):
            detail_test = self.test_detail_functionality(host, rule_info["detailUrl"])
            tests["detail"] = detail_test
            if detail_test["status"] == "error":
                result["critical_issues"].append("详情页异常，APP中无法获取视频详情")

        result["functionality_tests"] = tests

        # 4. APP使用体验预测
        app_predictions = self.predict_app_behavior(rule_info, connectivity, tests)
        result["app_predictions"] = app_predictions

        # 5. 性能评估
        response_time = connectivity.get("response_time", 0)
        if response_time > 5000:
            result["warnings"].append("响应时间超过5秒，APP中加载会很慢")
        elif response_time > 3000:
            result["warnings"].append("响应时间较慢，APP体验一般")

        # 6. 计算整体状态
        if result["critical_issues"]:
            result["overall_status"] = "error"
            result["app_usability"] = "unusable"
        elif result["warnings"] or any(
            t.get("status") == "error" for t in tests.values()
        ):
            result["overall_status"] = "warning"
            result["app_usability"] = "limited"
        else:
            result["overall_status"] = "success"
            result["app_usability"] = "good"

        # 7. 生成修复建议
        result["recommendations"] = self.generate_fix_recommendations(result)

        return result

    def predict_app_behavior(self, rule_info, connectivity, tests):
        """预测在APP中的表现"""
        predictions = {}

        # 首页加载预测 - 基于连通性和分类接口状态
        if connectivity.get("status") == "success":
            category_test = tests.get("category", {})
            if category_test and category_test.get("status") == "success":
                load_time = connectivity.get("response_time", 0)
                if load_time < 1000:
                    predictions["homepage"] = "首页加载流畅，内容正常显示"
                elif load_time < 3000:
                    predictions["homepage"] = "首页加载一般，内容正常显示"
                else:
                    predictions["homepage"] = "首页加载缓慢，但内容能正常显示"
            else:
                predictions["homepage"] = "首页连接成功但无法加载内容，会显示空白或错误"
        else:
            predictions["homepage"] = "首页完全无法加载"

        # 搜索功能预测
        search_test = tests.get("search", {})
        if search_test.get("status") == "success":
            if search_test.get("json_valid"):
                predictions["search"] = "搜索功能正常，能返回结果"
            elif search_test.get("has_content"):
                predictions["search"] = "搜索功能基本正常"
            else:
                predictions["search"] = "搜索功能可能异常，返回内容不足"
        else:
            predictions["search"] = "搜索功能无法使用"

        # 分类浏览预测
        category_test = tests.get("category", {})
        if category_test.get("status") == "success":
            predictions["category"] = "分类浏览正常"
        else:
            predictions["category"] = "分类列表可能无法显示"

        # 视频播放预测
        detail_test = tests.get("detail", {})
        if detail_test.get("status") == "success":
            predictions["playback"] = "视频详情获取正常，播放功能应该可用"
        else:
            predictions["playback"] = "视频详情获取异常，可能无法播放"

        # 整体体验预测
        working_functions = sum(
            1 for t in tests.values() if t.get("status") == "success"
        )
        total_functions = len(tests)

        if working_functions == total_functions:
            predictions["overall"] = "完整功能可用，APP体验良好"
        elif working_functions > total_functions * 0.6:
            predictions["overall"] = "主要功能可用，APP基本可用"
        else:
            predictions["overall"] = "多项功能异常，APP体验较差"

        return predictions

    def generate_fix_recommendations(self, result):
        """生成修复建议"""
        recommendations = []

        rule_info = result.get("rule_analysis", {})
        connectivity = result.get("connectivity_test", {})
        tests = result.get("functionality_tests", {})

        # 规则文件问题
        if rule_info.get("potential_issues"):
            for issue in rule_info["potential_issues"]:
                recommendations.append(f"修复规则文件: {issue}")

        # 连接问题
        if connectivity.get("status") == "error":
            recommendations.append("检查站点是否可用，或更新host地址")

        # 功能问题
        for func_name, test_result in tests.items():
            if test_result.get("status") == "error":
                recommendations.append(f"修复{func_name}功能的URL配置")

        # 性能问题
        response_time = connectivity.get("response_time", 0)
        if response_time > 3000:
            recommendations.append("站点响应慢，建议寻找更快的服务器或镜像站点")

        # 内容问题
        if connectivity.get("content_warning"):
            recommendations.append(f"页面内容异常: {connectivity['content_warning']}")

        return recommendations

    def test_all_sites(self, max_workers=None):
        """测试所有站点"""
        sites = self.load_sites()

        # 动态调整并发数：站点少时用2个线程，站点多时最多用4个线程
        if max_workers is None:
            max_workers = min(max(len(sites) // 8, 2), 4)

        print(f"🚀 开始完整功能测试，共{len(sites)}个站点，使用{max_workers}个并发线程")

        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            results = list(executor.map(self.comprehensive_site_test, sites))

        return results

    def generate_app_usage_report(
        self, results, output_file="tvbox_app_compatibility_report.md"
    ):
        """生成APP使用兼容性报告"""

        # 清理旧报告
        old_reports = glob.glob("*compatibility_report.md") + glob.glob("站点修复*.md")
        for report in old_reports:
            try:
                os.remove(report)
                print(f"🗑️ 删除旧报告: {report}")
            except Exception as e:
                print(f"⚠️ 删除报告失败 {report}: {e}")

        # 统计数据
        total = len(results)
        usable = len([r for r in results if r["app_usability"] == "good"])
        limited = len([r for r in results if r["app_usability"] == "limited"])
        unusable = len([r for r in results if r["app_usability"] == "unusable"])

        report = f"""# 📱 TVBox APP 站点兼容性报告

## 🎯 测试概览

**测试时间**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}  
**总站点数**: {total}  
**✅ 完全可用**: {usable} ({usable / total * 100:.1f}%)  
**⚠️ 部分可用**: {limited} ({limited / total * 100:.1f}%)  
**❌ 无法使用**: {unusable} ({unusable / total * 100:.1f}%)  

## 📊 APP体验预测

此报告模拟真实APP使用场景，预测每个站点在TVBox APP中的实际表现。

---

"""

        # 分类显示结果
        categories = [
            ("good", "✅ 完全可用站点", "这些站点在APP中功能完整，体验良好"),
            ("limited", "⚠️ 部分可用站点", "这些站点有部分功能异常，但基本可用"),
            ("unusable", "❌ 无法使用站点", "这些站点在APP中会出现严重问题或无法使用"),
        ]

        for status, title, description in categories:
            sites = [r for r in results if r["app_usability"] == status]
            if not sites:
                continue

            report += f"## {title} ({len(sites)}个)\n\n{description}\n\n"

            for site in sites:
                report += self.generate_site_app_report(site)
                report += "\n---\n\n"

        # 添加修复指南
        report += self.generate_fix_guide(results)

        with open(output_file, "w", encoding="utf-8") as f:
            f.write(report)

        print(f"📄 APP兼容性报告已生成: {output_file}")
        return report

    def generate_site_app_report(self, site):
        """生成单个站点的APP使用报告"""
        name = site["name"]
        key = site["key"]
        usability = site["app_usability"]

        # 状态图标
        status_icons = {"good": "✅", "limited": "⚠️", "unusable": "❌"}

        report = f"### {status_icons.get(usability, '❓')} {name} (`{key}`)\n\n"

        # APP使用体验预测
        predictions = site.get("app_predictions", {})
        if predictions:
            report += "**📱 APP中的表现预测:**\n"
            for func, prediction in predictions.items():
                report += f"- **{func}**: {prediction}\n"
            report += "\n"

        # 技术测试结果
        connectivity = site.get("connectivity_test", {})
        if connectivity.get("status") == "success":
            response_time = connectivity.get("response_time", 0)
            speed_icon = "🐌" if response_time > 3000 else "⚡"
            ssl_icon = "🔒" if connectivity.get("ssl") else "🔓"
            report += f"**🌐 连接状态**: {ssl_icon} {speed_icon} {response_time}ms\n\n"

        # 功能测试状态
        tests = site.get("functionality_tests", {})
        if tests:
            report += "**⚙️ 功能测试结果:**\n"
            for func, result in tests.items():
                status_icon = "✅" if result.get("status") == "success" else "❌"
                report += f"- {status_icon} {func}: {result.get('status', 'unknown')}\n"
            report += "\n"

        # 严重问题
        critical_issues = site.get("critical_issues", [])
        if critical_issues:
            report += "**🚨 严重问题 (会导致APP异常):**\n"
            for issue in critical_issues:
                report += f"- ❗ {issue}\n"
            report += "\n"

        # 警告
        warnings = site.get("warnings", [])
        if warnings:
            report += "**⚠️ 注意事项:**\n"
            for warning in warnings:
                report += f"- ⚠️ {warning}\n"
            report += "\n"

        # 修复建议
        recommendations = site.get("recommendations", [])
        if recommendations:
            report += "**🔧 修复建议:**\n"
            for rec in recommendations:
                report += f"- 💡 {rec}\n"
            report += "\n"

        return report

    def generate_fix_guide(self, results):
        """生成修复指南"""
        report = "## 🛠️ 问题修复指南\n\n"

        # 统计常见问题
        common_issues = {}
        for site in results:
            for issue in site.get("critical_issues", []):
                common_issues[issue] = common_issues.get(issue, 0) + 1

        if common_issues:
            report += "### 常见问题及影响\n\n"
            for issue, count in sorted(
                common_issues.items(), key=lambda x: x[1], reverse=True
            ):
                report += f"- **{issue}** (影响 {count} 个站点)\n"
            report += "\n"

        # 修复优先级建议
        report += """### 🎯 修复优先级建议

1. **高优先级**: 修复"无法解析"和"缺少host"的站点，这些会导致APP崩溃
2. **中优先级**: 修复搜索和分类功能异常的站点，影响主要功能
3. **低优先级**: 优化响应慢的站点，改善用户体验

### 📱 APP使用建议

- **推荐使用**: 完全可用的站点，功能稳定，体验良好
- **谨慎使用**: 部分可用的站点，某些功能可能异常
- **避免使用**: 无法使用的站点，会导致APP异常或崩溃

"""

        report += (
            f"---\n*报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*\n"
        )
        return report

    def cleanup_old_files(self):
        """清理旧的备份文件和报告"""
        print("🧹 清理旧文件...")

        old_backups = glob.glob("scripts/config_backup_*.json")
        for backup in old_backups:
            try:
                os.remove(backup)
                print(f"  🗑️ 删除旧备份: {backup}")
            except Exception as e:
                print(f"  ⚠️ 删除失败 {backup}: {e}")

        old_reports = glob.glob("*compatibility_report.md") + glob.glob("站点修复*.md")
        for report in old_reports:
            try:
                os.remove(report)
                print(f"  🗑️ 删除旧报告: {report}")
            except Exception as e:
                print(f"  ⚠️ 删除失败 {report}: {e}")

    def update_config_with_working_sites(self, results):
        """根据测试结果更新config.json，只保留可用站点"""
        print("🔄 开始根据测试结果更新配置文件...")

        # 清理旧文件
        self.cleanup_old_files()

        # 获取完整的原始配置
        full_config = self.load_full_config()

        # 找出所有可用站点的key
        working_keys = []
        for result in results:
            if result["app_usability"] == "good":
                working_keys.append(result["key"])

        print(f"✅ 发现 {len(working_keys)} 个可用站点: {working_keys}")

        # 筛选出可用的站点配置
        working_sites = []
        all_sites = full_config["sites"]

        for site in all_sites:
            if site["key"] in working_keys:
                working_sites.append(site)
                print(f"  ✅ 保留站点: {site['name']} ({site['key']})")
            else:
                print(f"  ❌ 移除站点: {site['name']} ({site['key']})")

        # 更新配置
        full_config["sites"] = working_sites

        # 备份原配置
        backup_path = (
            "scripts/config_backup_"
            + datetime.now().strftime("%Y%m%d_%H%M%S")
            + ".json"
        )
        try:
            with open(self.config_path, "r", encoding="utf-8") as f:
                backup_data = f.read()
            with open(backup_path, "w", encoding="utf-8") as f:
                f.write(backup_data)
            print(f"📁 原配置已备份到: {backup_path}")
        except Exception as e:
            print(f"⚠️ 备份失败: {e}")

        # 写入新配置
        try:
            with open(self.config_path, "w", encoding="utf-8") as f:
                json.dump(full_config, f, ensure_ascii=False, indent=2)
            print(f"🎉 配置文件已更新: {self.config_path}")
            print(
                f"📊 站点数量: {len(all_sites)} → {len(working_sites)} (精简了 {len(all_sites) - len(working_sites)} 个无效站点)"
            )
            return True
        except Exception as e:
            print(f"❌ 更新配置文件失败: {e}")
            return False


def main():
    """主函数"""
    import sys

    # 解析命令行参数
    auto_update = "--auto-update" in sys.argv or "-u" in sys.argv

    print("🔍 TVBox APP 完整功能测试器")
    if auto_update:
        print("🔄 自动更新模式: 将根据测试结果自动更新config.json")
    print("正在模拟真实APP使用场景，测试每个站点的实际表现...")

    tester = CompleteSiteTester()
    results = tester.test_all_sites()
    tester.generate_app_usage_report(results)

    # 显示简要统计
    total = len(results)
    usable = len([r for r in results if r["app_usability"] == "good"])
    limited = len([r for r in results if r["app_usability"] == "limited"])
    unusable = len([r for r in results if r["app_usability"] == "unusable"])

    print("\n✅ 测试完成!")
    print("📱 APP兼容性统计:")
    print(f"   完全可用: {usable}/{total} ({usable / total * 100:.1f}%)")
    print(f"   部分可用: {limited}/{total} ({limited / total * 100:.1f}%)")
    print(f"   无法使用: {unusable}/{total} ({unusable / total * 100:.1f}%)")
    print("\n📄 详细报告: tvbox_app_compatibility_report.md")

    # 自动更新配置文件
    if auto_update:
        print("\n" + "=" * 50)
        success = tester.update_config_with_working_sites(results)
        if success:
            print(f"🎉 配置文件自动更新完成！只保留了 {usable} 个可用站点")
        else:
            print("❌ 配置文件更新失败，请手动检查")
    else:
        print(
            "\n💡 提示: 使用 --auto-update 或 -u 参数可自动更新config.json，只保留可用站点"
        )


if __name__ == "__main__":
    main()
